<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * IF YOU MAKE SOME CHANGE TO THIS MODULE, THAT MEAN YOU KNOW WHAT YOU ARE DOING.
 * IF NOT, READ THE FUCKING MANUAL DUDE.
 */

/**
 Module Outlet Management ini telah didisain ulang dan sudah 100% sesuai dengan proses bisnis yang disampaikan pihak Smartfren.
 Rule yang terkait dengan modul outlet management antara lain:
 1 Hanya Cluster Coordinator (CC) dan Cluster Admin (CA) yang dapat menginput dan mengubah data outlet melalui web, 
   sedangkan sales dapat mengubah data outlet tertentu yang dikelolanya melalui handset masing-masing.
 2 Setiap outlet baru, harus direview oleh Cluster Admin (CA) kemudian data-data terkait dengan informasi outlet harus dilengkapi.
 3 Outlet yang aktif (Registered Outlet) ketika di edit tetap tercatat sebagai outlet aktif dan akan muncul di Journey Cycle,
   Record baru akan dibuat di table *unapproved untuk menampung infromasi-informasi tambahan dari outlet tersebut, dan informasi tersebut
   hanya akan berlaku setelah CC mengapprove perubahan yang dibuat.
 4 Proses approve akan menyalin semua record yang ada di tabel *unapproved ke tabel master masing-masing, 
   kemudian semua record dengan ID Outlet ybs akan dihapus dari table *unapproved
 5 Terdapat beberapa flag status yang berlaku pada tabel master dan tabel *unapproved. 
   # Pada tabel master istatus yang diakui adalah
     0  : Outlet baru dan data belum lengkap, semua outlet baru memiliki istatus 0
     1  : Hanya outlet dengan status ini yang dianggap aktif dan boleh/dapat dibuatkan Journey Cycle
     <0 : Outlet tidak aktif atau sudah didelete (dihapus).
   # Pada tabel *unapproved, istatus yang diakui adalah:
     0 : Outlet baru dan data belum lengkap, muncul di tab new dan hanya bisa dilihat oleh CA
     2 : Outlet baru dan data sudah lengkap, muncul di tab new dan hanya bisa dilihat oleh CC
     3 : Outlet edit dan data belum lengkap, muncul di tab edit dan hanya bisa dilihat oleh CA
     4 : Outlet edit dan data sudah lengkap, muncul di tab edit dan hanya bisa dilihat oleh CC
 * initiate by   : yaddisurahman@gmail.com
 * maintained by : yaddis@nutech-integrasi.com
 */

class Outlet extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->model('mglobal');
    $this->load->model('mmaster');
    $this->load->model('moutlet');
    $this->load->library('form_validation');
    $this->load->library("enc");  // encription module create by alfin.akhret@gmail.com
    $this->is_logged_in();
  }

  function is_logged_in() {
    $is_logged_in = $this->session->userdata('is_logged_in');
    if (!isset($is_logged_in) || $is_logged_in != true) {
      redirect(base_url() . 'index.php/login');
    }
  }

  public function index()
  {
    $template = 'shell/smooth';
    $data['main_view'] = 'partner/main_grids_outlet';
    
    $user_group_id = $this->session->userdata('group');
    $buttons_type  = $this->moutlet->getButtons(53, $user_group_id);  // yg ini hardcode, JANGAN DIUBAH !!!
    $active = array(); $edit = array(); $view = array();

    // Inisialisasi action button pada datatables
    // New    : View | Edit | Approve | Reject
    // Edit   : View | Edit | Approve | Reject
    // Active : View | Edit | Delete
    if($buttons_type['menu_view']) {
      $active[] = '<a class="btn-active viewBtnReg" href="'.base_url().'index.php/outlet/view/">View</a>';
      $edit[]   = '<a class="btn-edit viewBtnEdit" href="'.base_url().'index.php/outlet/view/">View</a>';
      $view[]   = '<a class="btn-view viewBtnNew" href="'.base_url().'index.php/outlet/view/">View</a>';   
    }
    if($buttons_type['menu_edit']) {
      $active[] = '<a class="btn-active updateBtnReg" href="'.base_url().'index.php/outlet/edit/">Edit</a>';
      $edit[]   = '<a class="btn-edit updateBtnEdit" href="'.base_url().'index.php/outlet/edit/">Edit</a>';
      $view[]   = '<a class="btn-view updateBtnNew" href="'.base_url().'index.php/outlet/edit/">Edit</a>'; 
    }
    if($buttons_type['menu_approve']) {
      $edit[] = '<a class="btn-edit approveBtnEdit" href="'.base_url().'index.php/outlet/approve/">Approve</a>';
      $view[] = '<a class="btn-view approveBtnNew" href="'.base_url().'index.php/outlet/approve/">Approve</a>'; 
    }
    if($buttons_type['menu_reject']) {
      $edit[] = '<a class="btn-edit rejectBtnEdit" href="'.base_url().'index.php/outlet/reject/">Reject</a>';
      $view[] = '<a class="btn-view rejectBtnNew" href="'.base_url().'index.php/outlet/reject/">Reject</a>'; 
    }
    if($buttons_type['menu_delete']) {
      $active[] = '<a class="btn-active deleteBtn" href="'.base_url().'index.php/outlet/delete/">Delete</a>';
    }
    
    // Karena kita punya tiga Tab pada outlet maka ada tiga menu juga, Okeh..!!
    $data['menu']['active'] = implode(" | ", $active);
    $data['menu']['edit']   = implode(" | ", $edit);
    $data['menu']['new']    = implode(" | ", $view);

    $this->load->view($template, $data);
  }

  /**
   * Proses penyimpanan untuk add() dan juga edit() menggunakan library form_validation(), silakan lihat manual CI untuk form validation.
   * Langkah-langkah pendaftaran outlet baru:
   * + Panggil semua variabel pelengkap "_initVars()"" yang kemudian ditampilkan di combo box 
   * + Pada dasarnya setiap input field yang ada form memiliki value tertentu, namun karena value-nya tidak ada maka harus diset dengan _blankVars()
   * Karena banyaknya parameter yang harus ditangkap saat proses penyimpanan, maka semua parameter tersebut dipindahkan ke method save() 
   * dengan mengikut sertakan beberapa variabel penting:
   * $data    : Adalah Array, yaitu semua variabel yang dikirim  atau ditampilkan ke view.
   * $istatus : Nilai istatus didapat dari input yang terdapat di laman view
   * $action  : Adalah String yang menyatakan proses, apakah data baru atau edit.
   */
  public function add()
  {
    $data["template"] = 'shell/smooth';
    $data['main_view']  = 'partner/outlet';
    $data['page_title'] = 'Penambahan Outlet';
    $data['init']       = $this->_blankVars();
    $data['complement'] = $this->_initVar();

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $data['program'] = $this->moutlet->getPrograms($cluster_id, array(1,3) );
    $data['outlet_programs'] = array();

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region']  = $teritori[0];
    $data['cluster'] = $teritori[1];

    if($this->input->post('data_complete') == 1) 
      { $istatus = 2; }  // Data baru sudah lengkap
    else 
      { $istatus = 0; }  // Data baru belum lengkap

    $this->save($data, $istatus, 'add', null);
  }

  /**
   * Yang paling berbeda pada method edit() adalah:
   * + Harus ada outlet_id yang akan diedit (dalam format yang terenkripsi, selanjutnya di dekrip dengan menggunakan pluginnya Bung Alfin)
   * + Karena outlet sudah memiliki data awal yang tersedia di database, maka semua field input harus diisi dengan data-data tersebut $data['init']
   *   tapi jika index $data tersebut 0, maka gantikan dengan _blankVars().
   */
  public function edit($oIdEncoded)
  {
    $outlet_id = $this->enc->defog(trim($oIdEncoded));
    $data["template"]   = 'shell/smooth';
    $data['main_view']  = 'partner/outlet';
    $data['complement'] = $this->_initVar();
    $initBlankVars      = $this->_blankVars();
    $data['page_title'] = "Perubahan data outlet $outlet_id";
    $data['init']['territory']  = $this->moutlet->getTerritory($outlet_id);
    $data['init']['frontliner'] = $this->moutlet->complements('t_mtr_outlet_frontliner', $outlet_id);
    $data['init']['branding']   = $this->moutlet->complements('t_mtr_outlet_branding', $outlet_id);
    $data['init']['outlet']     = $this->moutlet->complements('t_mtr_outlet', $outlet_id);
    $data['init']['owner']      = $this->moutlet->complements('t_mtr_outlet_owner', $outlet_id);
    $data['init']['oData']      = $this->moutlet->complements('t_mtr_outlet_data', $outlet_id);
    $data['init']['eloads']     = $this->moutlet->complement_mfino($outlet_id);
    $data['init']['oCategory']  = $this->moutlet->outletCtegory($outlet_id);
    // $data['init']['banks']      = $this->moutlet->complements('t_mtr_bank_account', $outlet_id);
    
    if(count($data['init']['branding']) == '0')
      { $data['init']['branding'] = $initBlankVars['branding']; }
    if(count($data['init']['owner']) == '0') 
      { $data['init']['owner'] = $initBlankVars['owner']; }
    if(count($data['init']['oData']) == '0') 
      { $data['init']['oData'] = $initBlankVars['oData']; }

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $data['program'] = $this->moutlet->getPrograms($cluster_id, array(1,3) );
    $data['outlet_programs'] = $this->moutlet->channelActivePrograms($outlet_id);

    $teritori = explode(' > ', $this->moutlet->channel_territory($outlet_id));
    $data['region']  = $teritori[0];
    $data['cluster'] = $teritori[1];

    $statusTmp = $data['init']['outlet']['istatus'];
    if($this->input->post('data_complete') == 1) {
      if($statusTmp == 2 OR $statusTmp == 0)
        { $istatus = 2; }   // Data New Outlet sudah lengkap
      else 
        { $istatus = 4; }   // Data Edit outlet sudah lengkap
    }
    else {
      if($statusTmp == 2 OR $statusTmp == 0)
        { $istatus = 0; }   // Data New Outlet belum lengkap
      else 
        { $istatus = 3; }   // Data Edit outlet belum lengkap
    }

      $this->save($data, $istatus, 'edit', null);

  }

  // Sama dengan edit() hanya saja proses simpan ditiadakan
  public function view($oIdEncoded)
  {
    $outlet_id = $this->enc->defog($oIdEncoded);
    $template  = 'shell/smooth';
    $data['main_view'] = 'partner/outlet';
    $data['complement'] = $this->_initVar();
    $initBlankVars      = $this->_blankVars();
    $data['page_title'] = "Detail data outlet $outlet_id";
    $data['init']['territory']  = $this->moutlet->getTerritory($outlet_id);
    $data['init']['frontliner'] = $this->moutlet->complements('t_mtr_outlet_frontliner', $outlet_id);
    $data['init']['branding']   = $this->moutlet->complements('t_mtr_outlet_branding', $outlet_id);
    $data['init']['outlet']     = $this->moutlet->complements('t_mtr_outlet', $outlet_id);
    $data['init']['owner']      = $this->moutlet->complements('t_mtr_outlet_owner', $outlet_id);
    $data['init']['oData']      = $this->moutlet->complements('t_mtr_outlet_data', $outlet_id);
    $data['init']['eloads']     = $this->moutlet->complement_mfino($outlet_id);
    $data['init']['oCategory']  = $this->moutlet->outletCtegory($outlet_id);

    // print_r($data); die();
    // $data['init']['eloads']     = $this->moutlet->complements('t_mtr_channel_eload', $outlet_id);

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $data['program'] = $this->moutlet->getPrograms($cluster_id, array(1,3) );
    $data['outlet_programs'] = $this->moutlet->channelActivePrograms($outlet_id);

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region']  = $teritori[0];
    $data['cluster'] = $teritori[1];

    if(count($data['init']['owner']) == '0') 
      { $data['init']['owner'] = $initBlankVars['owner']; }
    if(count($data['init']['branding']) == '0')
      { $data['init']['branding'] = $initBlankVars['branding']; }
    if(count($data['init']['oData']) == '0') 
      { $data['init']['oData'] = $initBlankVars['oData']; }
    $this->load->view($template, $data);
  }
  
  /**
   * @param  array  Prep variables yang akan ditampilkan di view, dikirim dari method add() dan edit()
   * @param  int    $istatus Flags
   *                         0: Outlet baru, data belum lengkap (CA harus edit lagi dan lengkapi data)
   *                         1: Approved/Active Outlets
   *                         2: Outlet baru, data sudah lengkap (CC bisa review, kemudian approve)
   *                         3: Outlet Edit, data belum lengkap (CA harus edit lagi dan lengkapi data)
   *                         4: Outlet Edit, data sudah lengkap (CC bisa review, kemudian approve)
   *                         5: -
   * @param  string $act     New Outlet        = null
   *                         Editing Outlet    = update
   *                         Approve an Outlet = approve
   *                         Delete an Outlet  = delete
   * @param  string $oId     Optional, new outlet doesn't have ID. So far this variable have no use
   * @return form_validation Jika input data salah maka akan ditampilkan informasi kesalahan dari form_validation
   */
  public function save($data, $istatus, $act = null, $oId = null )
  {

    // Outlet (12 params) ==========================================================================
    $mtr_oo["outlet_id"]          = $this->input->post('outlet_id');
    $mtr_oo["outlet_name"]        = $this->input->post('outlet_name');
    $mtr_oo["address"]            = $this->input->post('address');
    $mtr_oo["city"]               = $this->input->post('city');
    $mtr_oo["province_id"]        = $this->input->post('province');
    $mtr_oo["post_code"]          = $this->input->post('post_code');
    $mtr_oo["phone"]              = $this->input->post('outlet_phone');
    $mtr_oo["business_structure"] = $this->input->post('business_structure');
    $mtr_oo["istatus"]            = $istatus;
    $mtr_oo["outbond_caller_id"]  = $this->input->post('outbond_caller');

    // Outlet owner (12 params) ====================================================================
    $mtr_ow['owner_name']            = $this->input->post('owner_name');
    $mtr_ow['owner_gender']          = $this->input->post('owner_gender');
    $mtr_ow['owner_birth_place']     = $this->input->post('owner_birth_place');
    $mtr_ow['owner_birth_date']      = $this->input->post('owner_birth_date');
    $mtr_ow['owner_religion']        = $this->input->post('owner_religion');
    $mtr_ow['owner_email']           = $this->input->post('owner_email');
    $mtr_ow['owner_phone']           = $this->input->post('owner_phone');
    $mtr_ow['owner_identity_type']   = $this->input->post('owner_identity_type');
    $mtr_ow['owner_identity_number'] = $this->input->post('identity_number');
    $mtr_ow['istatus']               = $istatus;

    // Outlet data (15 params) =====================================================================
    $mtr_od["outlet_status"]            = $this->input->post('outlet_status');
    $mtr_od["outlet_type"]              = $this->input->post('tipe_outlet');
    $mtr_od["outlet_size"]              = $this->input->post('outlet_size');
    $mtr_od["outlet_location"]          = $this->input->post('outlet_location');
    $mtr_od["outlet_ownership"]         = $this->input->post('outlet_ownership');
    $mtr_od["outlet_smart_no"]          = $this->input->post('smart_no');
    $mtr_od["outlet_business_focus"]    = $this->input->post('business_focus');
    $mtr_od["outlet_customer_type"]     = $this->input->post('customer_type');
    $mtr_od["outlet_size_of_business"]  = $this->input->post('size_of_business');
    $mtr_od["outlet_is_expansion"]      = $this->input->post('is_expansion');
    $mtr_od["outlet_expansion_package"] = $this->input->post('expansion_pack');
    $mtr_od["istatus"]                  = $istatus;
    $mtr_od["outlet_building"]          = $this->input->post('outlet_building');

    // Outlet branding =============================================================================
    $mtr_bb['branding_status']   = $this->input->post('status_branding');
    $mtr_bb['full_branding_by']  = $this->input->post('full_branding_by');
    if($this->input->post('contract_end')) 
      { $mtr_bb['contract_end']  = $this->input->post('contract_end'); }
    else 
      { $mtr_bb['contract_end']  = null; }
    if($this->input->post('branding_value'))
      { $mtr_bb['branding_value'] = $this->input->post('branding_value'); }
    else 
      { $mtr_bb['branding_value'] = null; }
    $mtr_bb['istatus']            = $istatus;

    // Territory ===================================================================================
    $mtr_tt['parent_id']         = $this->mglobal->user_cluster($this->session->userdata('username'));
    $mtr_tt['territory_name']    = $this->input->post('outlet_name');;
    $mtr_tt['territory_type_id'] = 5; // khusus outlet gan, ini sudah dipatok. Jadi, JANGAN DIUBAH !!!

    if($this->input->post('maintaned_by') == null)
      { $mtr_tt['user_id'] = null; }
    else 
      { $mtr_tt['user_id'] = $this->input->post('maintaned_by'); }
    $mtr_tt['istatus']     = $istatus;

    // Eload dan MFino =============================================================================
    $eload_number = $this->input->post('eload_number');

    // Complement variables, harus dilengkapi untuk mempermudah pelacakan perubahan data ===========
    if($act == 'add') {
      $mtr_oo['created_by'] = $this->session->userdata('username');
      $mtr_oo['created_on'] = date('Y-m-d H:i:s');
      $mtr_ow['created_by'] = $this->session->userdata('username');
      $mtr_ow['created_on'] = date('Y-m-d H:i:s');
      $mtr_od['created_by'] = $this->session->userdata('username');
      $mtr_od['created_on'] = date('Y-m-d H:i:s');
      $mtr_tt['created_by'] = $this->session->userdata('username');
      $mtr_tt['created_on'] = date('Y-m-d H:i:s');
      $mtr_bb['created_by'] = $this->session->userdata('username');
      $mtr_bb['created_on'] = date('Y-m-d H:i:s');
    }
    else {
      $mtr_oo['updated_by'] = $this->session->userdata('username');
      $mtr_oo['updated_on'] = date('Y-m-d H:i:s');
      $mtr_ow['updated_by'] = $this->session->userdata('username');
      $mtr_ow['updated_on'] = date('Y-m-d H:i:s');
      $mtr_od['updated_by'] = $this->session->userdata('username');
      $mtr_od['updated_on'] = date('Y-m-d H:i:s');
      $mtr_tt['updated_by'] = $this->session->userdata('username');
      $mtr_tt['updated_on'] = date('Y-m-d H:i:s');
      $mtr_bb['updated_by'] = $this->session->userdata('username');
      $mtr_bb['updated_on'] = date('Y-m-d H:i:s');
    }

    // Outlet Programs =============================================================================
    $program_id = $this->input->post("program_id"); 
    $oId = $mtr_oo["outlet_id"];

    // Form Validation rules and data preps ========================================================
    $this->form_validation->set_rules('outlet_name'   , 'Nama Outlet'         , 'required|trim|htmlspecialchars');
    $this->form_validation->set_rules('address'       , 'Alamat Outlet'       , 'required|trim|htmlspecialchars');
    $this->form_validation->set_rules('city'          , 'Nama Kota'           , 'required|trim|htmlspecialchars');
    $this->form_validation->set_rules('outlet_phone'  , 'Nomor Telpon Outlet' , 'required|min_length[10]|max_length[13]|numeric|trim');
    $this->form_validation->set_rules('owner_phone'   , 'Nomor Telpon Pemilik', 'required|min_length[10]|max_length[13]|numeric|trim');
    $this->form_validation->set_rules('branding_value', 'Nilai Branding'      , 'numeric');
    // $this->form_validation->set_rules('eload_number[]', 'Nomor Eload'      , "required|min_length[10]|max_length[13]|numeric|trim");
    $this->form_validation->set_rules('eload_number[]', 'Nomor Eload'         , "callback_eload_validation[$oId]"); 

    /**
     * All sequences goes to t_mtr_*_unapproved
     * 1. Territory
     * 2. Outlet
     * 3. Outlet Data
     * 4. Owner
     * 5. Brandings
     * 6. Eload
     * 7. Outlet and Cluster Programs
     */
    
    // "IF" yang pertama adalah yang dieksekusi pertama kali, yaitu sebelum form disubmit
    // dan setelah form disumbit dan terdapat kesalahan input data
    // Jika semua input sudah benar maka lanjutkan dengan proses simpan
    if ($this->form_validation->run() == false) {
      $this->load->view($data["template"], $data);
    }
    else {
      $this->db->trans_begin();

      if($act == 'add') { 
        $sp_outlet = $this->moutlet->generate_outlet_id($mtr_oo["outlet_name"], $mtr_tt['parent_id'], $mtr_tt['user_id'], $mtr_oo["address"], $mtr_oo["city"], $mtr_od["outlet_business_focus"]);
        $oId = explode(' ', $sp_outlet); // index [2]
        $mtr_oo["outlet_id"] = $oId[2];
        // die();
      }

      $outlet_id              = $this->moutlet->save_outlet($mtr_oo, $mtr_oo["outlet_id"]);
      $territory_id           = $this->moutlet->save_territory($mtr_tt, $mtr_oo["outlet_id"]);

      /* Data preparation for eload. My objective is, I want to have an array like below:
      *  Array (
      *    [0] => ('channel_id', 'territory_id', 'eload_number', 'istatus'),
      *    [1] => ('channel_id', 'territory_id', 'eload_number', 'istatus'),
      *    [...] => (...)
      *  )
      */ 
      $i = 0;
      foreach ($eload_number as $key) {
        if($key != null OR $key != '-' OR $key != 0) {
          $mtr_ee[$i]["outlet_id"]   = $mtr_oo["outlet_id"];
          $mtr_ee[$i]['territory_id'] = $territory_id;
          $mtr_ee[$i]["eload_number"] = $this->_phone_number($key);
          if($act == 'add') {
            $mtr_ee[$i]['created_by'] = $this->session->userdata('username');
            $mtr_ee[$i]['created_on'] = date('Y-m-d H:i:s');
          }
          else {
            $mtr_ee[$i]['updated_by'] = $this->session->userdata('username');
            $mtr_ee[$i]['updated_on'] = date('Y-m-d H:i:s');
          }
          $i++;
        }
      }

      $this->moutlet->saveDatas($mtr_od, 't_mtr_outlet_data_unapproved', $mtr_oo["outlet_id"]);
      $this->moutlet->saveDatas($mtr_ow, 't_mtr_outlet_owner_unapproved', $mtr_oo["outlet_id"]);
      $this->moutlet->saveDatas($mtr_bb, 't_mtr_outlet_branding_unapproved', $mtr_oo["outlet_id"]);

      $this->moutlet->saveEload($mtr_ee, $mtr_oo["outlet_id"]);
      $this->moutlet->savePrograms($program_id, $mtr_oo["outlet_id"]);
 
      if ($this->db->trans_status() === FALSE)
        { $this->db->trans_rollback(); }
      else { 
        $this->db->trans_commit(); 
        redirect(base_url('index.php/outlet'));
        $this->session->set_flashdata('div_class', 'success');
        $this->session->set_flashdata('message', 'Input data outlet berhasil dengan kode outlet '. $mtr_oo["outlet_id"]);
      }
    } // End of form_validation

  } // End of save

  function eload_validation($param, $oId = null)
  {
    if(substr(trim($param), 0, 2) == '62')
      { $param = substr(trim($param), 2); }
    $eXst = $this->moutlet->eXst($param, $oId); // must true to be true
    if(!trim($param))
      { 
        $this->form_validation->set_message('eload_validation', 'Nomor eload harus diisi');
        return false;
      }
    else if (substr($param, 0, 2) != '88')
      { 
        $this->form_validation->set_message('eload_validation', 'Format Eload tidak valid');
        return false;
      }
    else if( strlen($param) < 10 OR strlen($param) > 13 )
      { 
        $this->form_validation->set_message('eload_validation', 'Panjang Eload harus antara 10 dan 13 karakter');
        return false;
      }
    else if(!preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $param))
      { 
        $this->form_validation->set_message('eload_validation', 'Nomor Eload harus mengggunakan format numerik, karakter selain angka tidak diperbolehkan');
        return false;
      }
    else if(!$eXst)
      { 
        $this->form_validation->set_message('eload_validation', 'Nomor Eload tidak valid, sudah pernah digunakan oleh outlet/agent lain');
        return false;
      }
    else
      { return true; }
  }

  /**
   * Proses approve() menyalin semua data yang ada di tabel *unapparoved ke tabel master. 
   * Kemudian data dengan outlet_id yang ada di *unapparoved dihapus.
   * @param  [string] $oIdEncoded [outlet_id dalam format ter enkripsi]
   */
  public function approve($oIdEncoded) {
    $db_sri = $this->load->database('Retails', TRUE);
    $this->load->model('mintegrasi');
    $outlet_id = $this->enc->defog($oIdEncoded);
    
    $this->db->trans_begin();

    $this->moutlet->approve($outlet_id);

    $db_sri->trans_begin();
    $this->mintegrasi->partner($outlet_id, 'outlet');
    $this->mintegrasi->userSync($outlet_id);

    if ($this->db->trans_status() === FALSE OR $db_sri->trans_status() === FALSE) { 
      $this->db->trans_rollback();
      $db_sri->trans_rollback();
      $trans_status = false;
      $this->session->set_flashdata("div_class", "error");
      $this->session->set_flashdata("message", "$outlet_id gagal diapproved");
    }
    else { 
      $this->db->trans_commit();
      $db_sri->trans_commit();
      $trans_status = true;
      $this->session->set_flashdata("div_class", "success");
      $this->session->set_flashdata("message", "$outlet_id berhasil diapproved");
    }
    redirect(base_url('index.php/outlet'));
  }

  /**
   * Outlet yang dapat direject hanya data yang berasal dari tabel *unapproved. 
   * Dengan direjectnya data, maka akan menghapus data tersebut dari tabel *unapproved 
   * @param  [string] $oIdEncoded [outlet_id dalam format ter enkripsi]
   */
  public function reject($oIdEncoded) {
    $outlet_id = $this->enc->defog($oIdEncoded);
    $this->db->trans_begin();

    $this->moutlet->reject($outlet_id);

    if ($this->db->trans_status() === FALSE) { 
      $this->db->trans_rollback(); 
      $trans_status = false;
      $this->session->set_flashdata("div_class", "error");
      $this->session->set_flashdata("message", "$outlet_id gagal dihapus");
    }
    else { 
      $this->db->trans_commit(); 
      $trans_status = true;
      $this->session->set_flashdata("div_class", "success");
      $this->session->set_flashdata("message", "$outlet_id berhasil dihapus");
    }
    redirect(base_url('index.php/outlet'));
  }

  /**
   * Outlet yang dapat dihapus hanya data yang berasal dari tabel master
   * Dengan dihapusnya data, maka akan mengubah istatus menjadi -5
   * @param  [string] $oIdEncoded [outlet_id dalam format ter enkripsi]
   */
  public function delete($oIdEncoded) {
    $outlet_id = $this->enc->defog($oIdEncoded);
    $this->db->trans_begin();

    $this->moutlet->delete_outlet($outlet_id);

    if ($this->db->trans_status() === FALSE) { 
      $this->db->trans_rollback(); 
      $trans_status = false;
      $this->session->set_flashdata("div_class", "error");
      $this->session->set_flashdata("message", "$outlet_id gagal dihapus");
    }
    else { 
      $this->db->trans_commit(); 
      $trans_status = true;
      $this->session->set_flashdata("div_class", "success");
      $this->session->set_flashdata("message", "$outlet_id berhasil dihapus");
    }
    redirect(base_url('index.php/outlet'));
  }

  /**
   * Ini adalah proses inisialisasi variable kosong, setiap index dari array mewakili field name di database
   * @return Array
   */
  private function _blankVars() {
    $data['territory'] = array(
      'territory_id' => null, 'territory_name' => null, 'parent_id' => null, 'user_id' => null, 'istatus' => null
    );
    $data["outlet"] = array(
      'outlet_id' => null, 'territory_id' => null, 'outlet_name' => null, 'address' => null, 
      'city' => null, 'province_id' => null, 'post_code' => null, 'phone' => null, 
      'business_structure' => null, 'istatus' => null, 'outbond_caller_id' => null, "eload_number" => null
    );
    $data['branding'] = array(
      'branding_status' => null, 'full_branding_by' => null, 'contract_end' => null, 'branding_value' => null
    );
    $data['owner'] = array(
      'outlet_owner_id' => null, 'outlet_id' => null, 'owner_name' => null, 'owner_gender' => null, 
      'owner_birth_place' => null, 'owner_birth_date' => null, 'owner_religion' => null, 
      'owner_email' => null, 'owner_phone' => null, 'owner_identity_type' => null, 
      'owner_identity_number' => null, 'istatus' => null
    );
    $data['oData'] = array(
      'outlet_data_id' => null, 'outlet_id' => null, 'outlet_status' => null, 'outlet_type' => null, 
      'outlet_size' => null, 'outlet_location' => null, 'outlet_employee_number' => null, 
      'outlet_lifetime' => null, 'outlet_ownership' => null, 'outlet_smart_no' => null, 'outlet_business_focus' => null, 
      'outlet_customer_type' => null, 'outlet_size_of_business' => null, 'outlet_is_expansion' => null, 
      'outlet_expansion_package' => null, 'outlet_join_lajang' => null, 'outlet_lajang_package' => null, 
      'outlet_lajang_is_reorder' => null, 'outlet_building' => null, 'istatus' => null
    );
    $data['banks'] = array(
      'bank_account_id' => null, 'territory_id' => null, 'bank_name' => null, 'bank_branch' => null, 
      'bank_account_name' => null, 'bank_account_number' => null, 'istatus' => null
    );

    $data['frontliner'] = array(
      'outlet_frontliner_id' => null, 'outlet_id' => null, 'frontliner_code' => null, 'frontliner_type' => null, 
      'frontliner_name' => null, 'frontliner_gender' => null, 'frontliner_birth_place' => null, 
      'frontliner_birth_date' => null, 'frontliner_identity_type' => null, 'frontliner_identity_no' => null, 
      'frontliner_religion' => null, 'frontliner_work_experience' => null, 'frontliner_marital_status' => null, 
      'frontliner_referral_sales' => null, 'frontliner_address' => null, 'frontliner_city' => null, 
      'frontliner_province_id' => null, 'frontliner_zip_code' => null, 'frontliner_mdn_smartfren' => null, 
      'frontliner_remark' => null, 'istatus' => null
    );

    $data['eloads'][0] = array(
      'channel_id' => null, 'territory_id' => null, 'user_mfino' => null, 'eload_number' => null, 'istatus' => null
    );
    return $data;
  }

  /**
   * Inisialisasi variable pelengkap untuk menghasilkan value di combo box dan lain sebagainya
   * sebagian besar diambil dari t_mtr_lookup
   * @return Array
   */
  private function _initVar()
  {

    $fields = array(
      'business_focus','business_structure','customer_type',
      'education_type','event_selling','expansion_list',
      'gender','identity_type','lajang_list','marital_status',
      'outlet_class_amount','outlet_location','outlet_ownership',
      'full_branding_by',// 'outlet_serial_length',
      'outlet_size','outlet_status','outlet_type','position',
      'religion','size_of_business','tipe_outlet', 'frontliner_type',
      'outlet_category_ho'  
    );
    $vars = $this->moutlet->initVars($fields);
    $data  = array();
    $x = 0;
    foreach ($vars as $key) {
      if( end(array_keys($data)) !=  $key->lookup_key) {
        $x = 0;
        $data[$key->lookup_key][$x]['field_key'] = $key->lookup_value;
        $data[$key->lookup_key][$x++]['field_val'] = $key->lookup_desc;
      }
      else { 
        $data[$key->lookup_key][$x]['field_key'] = $key->lookup_value;
        $data[$key->lookup_key][$x++]['field_val'] = $key->lookup_desc;
      }
    }
    $data['province'] = $this->moutlet->get_province();

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    // sales person adalah sales yang memamtain outlet. tampilkan semua sales berdasarkan ID Cluster dan User Group sales
    $data['sales_person']   = $this->mglobal->get_sales($cluster_id, array(8, 35)); // 8: SFA, 35: SGA
    $data['outbond_caller'] = $this->mglobal->get_sales($cluster_id, array(7));

    return $data;
  }

  private function _eload_prep()
  {
    # code...
  }

  /**
   * Proses penambahan atau edit data frontliner
   * @param  string   $param  add/edit
   * @param  string   $id     can be Outlet ID or SSC ID
   * @return
   */
  public function frontliner($action, $id)
  {
    if($action == 'add')
      { $data['page_title'] = "Penambahan data frontliner"; }
    else
      { $data['page_title'] = "Perubahan data frontliner"; }
    $template  = 'shell/smooth';
    $data['main_view']  = 'partner/outlet_frontliner_form';
    $data['complement'] = $this->_initVar();
    $data['init']       = $this->_blankVars();
    if($action == 'add')
      { $data['outlet_id']  = $id; }

    $this->save_frontliner($action, $id);

    $this->load->view($template, $data);
  }

  public function save_frontliner($action, $outlet_id){

    if($action == 'add') { 
      $data['outlet_id']  = $this->input->post('frontliner_outlet_id'); 
      $data['created_by'] = $this->session->userdata('username');
      $data['created_on'] = date("Y-m-d H:i:s");
    }
    else {
      $data['updated_by'] = $this->session->userdata('username');
      $data['updated_on'] = date("Y-m-d H:i:s");
    }
    $data['frontliner_type']            = $this->input->post('frontliner_type');
    $data['frontliner_name']            = $this->input->post('frontliner_name');
    $data['frontliner_gender']          = $this->input->post('frontliner_gender');
    $data['frontliner_address']         = nl2br($this->input->post('frontliner_address'));
    $data['frontliner_city']            = trim($this->input->post('frontliner_city'));
    $data['frontliner_birth_place']     = trim($this->input->post('frontliner_birth_place'));
    $data['frontliner_birth_date']      = $this->input->post('frontliner_birth_date');
    $data['frontliner_identity_type']   = $this->input->post('frontliner_identity_type');
    $data['frontliner_identity_no']     = $this->input->post('frontliner_identity_no');
    $data['frontliner_religion']        = $this->input->post('frontliner_religion');
    // $data['frontliner_work_experience'] = intval($this->input->post('front_work_experience'));
    $data['frontliner_marital_status']  = $this->input->post('frontliner_marital_status');
    $data['frontliner_province_id']     = $this->input->post('frontliner_province_id');
    $data['frontliner_zip_code']        = $this->input->post('frontliner_zip_code');
    $data['frontliner_mdn_smartfren']   = $this->_phone_number($this->input->post('frontliner_mdn_smartfren'));
    $data['frontliner_remark']          = nl2br($this->input->post('frontliner_remark'));

    foreach ($data as $key => $val) {
      if($val == null)
        $data[$key] = null;
    }

    $this->form_validation->set_rules('frontliner_name', 'Nama Frontliner', 'required|trim');
    $this->form_validation->set_rules('frontliner_address', 'Alamat', 'required|trim');

    if($this->form_validation->run() == true) {
      $status = $this->moutlet->save_frontliner($data, $action);
      if($status) {
        redirect(base_url('index.php/outlet/edit/').'/'.$this->enc->fogit($data['outlet_id']));
      }
    }
  }

  private function _phone_number($phone_number) {
    $phone_number = trim($phone_number);
    if($phone_number != "0") 
    {
      if(substr($phone_number, 0, 3) == '+62')
        { $phone_number = '62'.substr($phone_number, 3); }
      elseif(substr($phone_number, 0, 1) == 0 ) {
        $phone_number = '62'.substr($phone_number, 1);
      }
      elseif(substr($phone_number, 0, 1) != 0 && substr($phone_number, 0, 2) != 62) {
        $phone_number = '62'.$phone_number;
      }
    }
    else 
      { $phone_number = null; }
    return $phone_number;
  }
  

  /**
   * Method untuk menambahkan kategori outlet yang hanya bisa diakses oleh Head Office officer
   * @param  string $act         add/delete
   * @param  int    $id          decoded record_id
   * @return
   */
  public function category($act = null, $eId = null) {
    $data["template"]  = "shell/smooth";
    if($act == 'add') {
      $data['page_title'] = "Penambahan Kategori Outlet";
      $data['regions']    = $this->moutlet->get_region();
      $data['main_view']  = "partner/outlet_category_add";
      $data['categories'] = $this->moutlet->getPrograms($this->session->userdata('cluster_id'), array(5));
      $teritori = explode('>', $this->mglobal->getTerritoryPath());
      $data['region']  = $teritori[0];
    }
    else {
      $data['main_view']  = "partner/outlet_category";
      $data['page_title'] = "Data Kategori Outlet";
    }

    if($act == 'add') {
      $category   = $this->input->post('categories');
      $cluster_id = $this->input->post('clusters');
      $program_id = $this->input->post('program');

      $this->form_validation->set_rules('categories[]', 'ID Outlet', 'required');

      if ($this->form_validation->run() == false) {
        $this->load->view($data["template"], $data);
      }
      else {
        $x = 0;
        $program = array();
        foreach ($category as $key) {
          $id = explode('_', $key);
          $channel_id = $this->moutlet->valid_outlet_category($id[0]);
          if($channel_id == 0) {
            $program[$x]['channel_id']   = $id[0];
            $program[$x]['territory_id'] = $id[1];
            $program[$x]['program_id']   = $program_id;
            $program[$x]['created_by']   = $this->session->userdata('username');
            $program[$x++]['created_on'] = date('Y-m-d H:i:s');
          }
        }
        if(count($program) != 0)
        {
          $status = $this->moutlet->save_category($program);

          if($status) 
            { 
              $this->session->set_flashdata('message', 'Insert data berhasil'); 
              $this->session->set_flashdata("div_class", "success");
            }
          else
            { 
              $this->session->set_flashdata('message', 'Insert data tidak berhasil');
              $this->session->set_flashdata("div_class", "error");
            }
        }
        else
          { 
            $this->session->set_flashdata('message', 'Simpan data tidak berhasil, semua outlet sudah terdaftar pada kategori tertentu');
            $this->session->set_flashdata("div_class", "error");
          }

        redirect(base_url().'index.php/outlet/category');
      }
    } // end of add

    elseif ($act == 'delete') {

      $record_id = $this->enc->defog($eId);
      $status = $this->moutlet->delete_outlet_category($record_id);
      if($status) 
        { 
          $this->session->set_flashdata('message', 'Data berhasil dihapus'); 
          $this->session->set_flashdata("div_class", "success");
        }
      else
        { 
          $this->session->set_flashdata('message', 'Data gagal dihapus');
          $this->session->set_flashdata("div_class", "error");
        }
      redirect(base_url().'index.php/outlet/category');
    }

    else {
      $this->load->view($data['template'], $data, FALSE);
    }

  }

  public function get_cluster()
  {
    $territory_id = $this->input->post('region_id');
    $cluster = $this->moutlet->get_cluster($territory_id);
    echo json_encode($cluster);
  }

  public function load_outlet() {
    $cluster_id = $this->input->post('cluster_id');
    $keyword    = strtoupper(trim($this->input->post('keyword')));

    $outlet     = $this->moutlet->load_outlet($cluster_id, $keyword);
    echo json_encode($outlet);
  }

  /**
   * DATATABLES
   * IF YOU ARE NOT AN EXPERT YOU SHOULD USE CODEIGNITER DATATABLES LIBRARY, IT IS MUCH EASIER !!!
   */
  public function gridRegOutlet()
  {
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));

    $aColumns = array( 'oo.outlet_id', 'oo.outlet_name', 'oo.address', 'f_get_user(tt.user_id) as user_id' );
    $sIndexColumn = "oo.outlet_id";
    $sTable = " t_mtr_outlet oo join t_mtr_territory tt on tt.territory_id = oo.territory_id ";

    $sLimit = "";

    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
      $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
        intval( $_GET['iDisplayStart'] );
    }

    if ( isset( $_GET['iSortCol_0'] ) )
    {
      $sOrder = "ORDER BY  ";
      for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
        {
          $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
            ".($_GET['sSortDir_'.$i]==='desc' ? 'asc' : 'desc').", ";
        }
      }

      $sOrder = substr_replace( $sOrder, "", -2 );
      if ( $sOrder == "ORDER BY " )
        { $sOrder = ""; }
    }
     
    $sWhere = " WHERE tt.parent_id = $cluster_id AND oo.istatus = 1 ";
    if ( $_GET['sSearch'] != "" )
    {
      $sWhere = "WHERE tt.parent_id = $cluster_id AND oo.istatus = 1 AND (";
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $_GET['bSearchable_'.$i] == "true" )
          { $sWhere .= $aColumns[$i]." ILIKE '%".( $_GET['sSearch'] )."%' OR "; }
      }
      $sWhere = substr_replace( $sWhere, "", -3 );
      $sWhere .= ")";
    }
     
    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != null )
      {
        if ( $sWhere == "" )
          { $sWhere = "WHERE "; }
        else
          { $sWhere .= " AND "; }
        $sWhere .= $aColumns[$i]." ILIKE '%".($_GET['sSearch_'.$i])."%' ";
      }
    }
     
    $sQuery = "
      SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
      FROM   $sTable
      $sWhere
      $sOrder
      $sLimit
    ";
    $rResult = $this->db->query($sQuery); 
    // $rResult->result_array();
    $sQuery = "
      SELECT COUNT (*) AS numrows
      FROM   $sTable
      WHERE tt.parent_id = $cluster_id and oo.istatus = 1
    ";
    $rResultTotal = $this->db->query($sQuery)->row(); 
    $iTotal = $rResultTotal->numrows;
     
    if ( $sWhere != "" )
    {
        $sQuery = "
          SELECT COUNT (*) AS numrows
          FROM   $sTable
          $sWhere
        ";
        $rResultFilterTotal = $this->db->query($sQuery)->row(); 
        $iFilteredTotal = $rResultFilterTotal->numrows;
    }
    else
    { $iFilteredTotal = $iTotal; }

    // Generating outputs
    $output = array(
      "sEcho" => intval($_GET['sEcho']),
      "iTotalRecords" => $iTotal,
      "iTotalDisplayRecords" => $iFilteredTotal,
      "aaData" => array()
    );

    // $j=$_GET['iDisplayStart'] ;
    foreach ($rResult->result_array() as $aRow  )
    {
      $row = array();
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $aColumns[$i] != null )
        {
          $colName = explode('as ', $aColumns[$i]);
          if(count($colName) > 1 )
            { $colName = $colName[1]; }
          else {
            $colName = explode('.', $aColumns[$i]);
            $colName = $colName[1];
          }
          $row[] = $aRow[ $colName ];
          // foreach ($row as $key) {
          //   $row[0] = $this->enc->fogit($key[0]);
          // }
        }
      }
      $output['aaData'][] = $row;
    }
    echo json_encode( $output );
  }

  public function gridUnapproved($flag)
  {
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));

    $aColumns = array( 'oo.outlet_id', 'oo.outlet_name', 'oo.address', 'f_get_user(tt.user_id) as user_id' );
    $sIndexColumn = "oo.outlet_id";
    $sTable = " t_mtr_outlet_unapproved oo join t_mtr_territory_unapproved tt on tt.territory_id = oo.territory_id ";

    $sLimit = "";

    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
      $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
        intval( $_GET['iDisplayStart'] );
    }

    if ( isset( $_GET['iSortCol_0'] ) )
    {
      $sOrder = "ORDER BY  ";
      for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
        {
          $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
            ".($_GET['sSortDir_'.$i]==='desc' ? 'asc' : 'desc').", ";
        }
      }

      $sOrder = substr_replace( $sOrder, "", -2 );
      if ( $sOrder == "ORDER BY " )
        { $sOrder = ""; }
    }
     
    $sWhere = " WHERE tt.parent_id = $cluster_id AND oo.istatus = $flag ";
    if ( $_GET['sSearch'] != "" )
    {
      $sWhere = "WHERE tt.parent_id = $cluster_id AND oo.istatus = $flag AND (";
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $_GET['bSearchable_'.$i] == "true" )
          { $sWhere .= $aColumns[$i]." ILIKE '%".( $_GET['sSearch'] )."%' OR "; }
      }
      $sWhere = substr_replace( $sWhere, "", -3 );
      $sWhere .= ")";
    }
     
    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != null )
      {
        if ( $sWhere == "" )
          { $sWhere = "WHERE "; }
        else
          { $sWhere .= " AND "; }
        $sWhere .= $aColumns[$i]." ILIKE '%".($_GET['sSearch_'.$i])."%' ";
      }
    }
     
    $sQuery = "
      SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
      FROM   $sTable
      $sWhere
      $sOrder
      $sLimit
    ";
    $rResult = $this->db->query($sQuery); 
    // $rResult->result_array();

    $sQuery = "
      SELECT COUNT (*) AS numrows
      FROM   $sTable
      WHERE tt.parent_id = $cluster_id and oo.istatus = $flag
    ";
    $rResultTotal = $this->db->query($sQuery)->row(); 
    $iTotal = $rResultTotal->numrows;
     
    if ( $sWhere != "" )
    {
        $sQuery = "
          SELECT COUNT (*) AS numrows
          FROM   $sTable
          $sWhere
        ";
        $rResultFilterTotal = $this->db->query($sQuery)->row(); 
        $iFilteredTotal = $rResultFilterTotal->numrows;
    }
    else
    { $iFilteredTotal = $iTotal; }

    // Generating outputs
    $output = array(
      "sEcho" => intval($_GET['sEcho']),
      "iTotalRecords" => $iTotal,
      "iTotalDisplayRecords" => $iFilteredTotal,
      "aaData" => array()
    );

    // $j=$_GET['iDisplayStart'] ;
    foreach ($rResult->result_array() as $aRow  )
    {
      $row = array();
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $aColumns[$i] != null )
        {
          $colName = explode('as ', $aColumns[$i]);
          if(count($colName) > 1 )
            { $colName = $colName[1]; }
          else {
            $colName = explode('.', $aColumns[$i]);
            $colName = $colName[1];
          }
          $row[] = $aRow[ $colName ];
          // foreach ($row as $key) {
          //   $row['fogs'] = $this->enc->fogit($key[0]);
          // }
        }
      }

      $output['aaData'][] = $row;
    }
    echo json_encode( $output );
  }

  public function gridOutletCategory()
  {
    $aColumns = array( 
        'cp.channel_program_id','cp.channel_id','tt.territory_name','tt.user_id',
        'f_get_user (tt.user_id) as user_name','pp.caption',  
        'split_part(f_get_territory_path(tt.parent_id), \' > \', 1) as region_name', 
        'split_part(f_get_territory_path(tt.parent_id), \' > \', 2) as cluster_name'
      );
    $sIndexColumn = " cp.channel_program_id ";
    $sTable = " t_mtr_channel_program cp join t_mtr_program pp on pp.program_id = cp.program_id JOIN t_mtr_territory tt ON tt.territory_id = cp.territory_id";

    $sLimit = "";

    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
      $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
        intval( $_GET['iDisplayStart'] );
    }

    if ( isset( $_GET['iSortCol_0'] ) ) {
      $sOrder = "ORDER BY  ";
      for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {

        // print_r($aColumns[ intval( $_GET['iSortCol_'.$i] ) ]);
        $xSortby = explode(' as ', ($aColumns[ intval( $_GET['iSortCol_'.$i] ) ]));
        if(count($xSortby) > 1 )
          { $s_sortby = $xSortby[1]; }
        else {
          { $s_sortby = $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]; }
        }
        // print_r($s_sortby);

        if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
          $sOrder .= $s_sortby. "
            ".($_GET['sSortDir_'.$i]==='desc' ? 'asc' : 'desc').", ";
        }
      }

      $sOrder = substr_replace( $sOrder, "", -2 );
      if ( $sOrder == "ORDER BY" )
        { $sOrder = ""; }
    }
     
    $sWhere = " ";
    if ( $_GET['sSearch'] != "" )
    {
      $sWhere = "WHERE (";
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        $kolom = explode(' as', $aColumns[$i]);
        if ( $_GET['bSearchable_'.$i] == "true" )
          { $sWhere .= $kolom[0]." ILIKE '%".( $_GET['sSearch'] )."%' OR "; }
      }
      $sWhere = substr_replace( $sWhere, "", -3 );
      $sWhere .= ")";
    }
     
    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != null )
      {
        if ( $sWhere == "" )
          { $sWhere = "WHERE "; }
        else
          { $sWhere .= " AND "; }
        $sWhere .= $aColumns[$i]." ILIKE '%".($_GET['sSearch_'.$i])."%' ";
      }
    }
     
    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = $this->db->query($sQuery); 
    // $rResult->result_array();

    $sQuery = "
        SELECT COUNT (*) AS numrows
        FROM   $sTable
    ";
    $rResultTotal = $this->db->query($sQuery)->row(); 
    $iTotal = $rResultTotal->numrows;
     
    if ( $sWhere != "" )
    {
        $sQuery = "
            SELECT COUNT (*) AS numrows
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = $this->db->query($sQuery)->row(); 
        $iFilteredTotal = $rResultFilterTotal->numrows;
    }
    else
    { $iFilteredTotal = $iTotal; }

    // Generating outputs
    $output = array(
      "sEcho" => intval($_GET['sEcho']),
      "iTotalRecords" => $iTotal,
      "iTotalDisplayRecords" => $iFilteredTotal,
      "aaData" => array()
    );

    // $j=$_GET['iDisplayStart'] ;
    foreach ($rResult->result_array() as $aRow  )
    {
      $row = array();
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $aColumns[$i] != null )
        {
          $colName = explode(' as ', $aColumns[$i]);
          if(count($colName) > 1 )
            { $colName = $colName[1]; }
          else {
            $colName = explode('.', $aColumns[$i]);
            $colName = $colName[1];
          }
          $row[] = $aRow[ $colName ];
          // foreach ($row as $key) {
          //   $row['fogs'] = $this->enc->fogit($key[0]);
          // }
        }
      }

      $output['aaData'][] = $row;
    }
    echo json_encode( $output );
  }

  public function fogit()
  {
    $term = $this->input->post('outlet_id');
    $result = $this->enc->fogit($term);
    echo $result;
  }
}

/* End of file outlet.php */
/* Location: ./application/controllers/outlet.php */
